<template>
	<view class="content">
		<view class="container">
			<view class="form-card">
				<view class="form-title">个人发票开具</view>

				<!-- 购方和销方信息 - 左右布局 -->
				<view class="info-container">
					<!-- 购方信息 -->
					<view class="info-section">
						<view class="section-title">购方信息</view>

						<view class="form-group">
							<view class="form-label">购方名称 <text class="required">*</text></view>
							<input class="form-input"
								placeholder="请输入购方名称" :value="formData.ghdwmc" @input="(e) => handleInputChange(e, 'ghdwmc')" />
						</view>

						<view class="form-group">
							<view class="form-label">购方电话 <text class="required">*</text></view>
							<input class="form-input"
								placeholder="请输入联系电话" :value="formData.ghdwdh" @input="(e) => handleInputChange(e, 'ghdwdh')" />
						</view>

						<view class="form-group">
							<view class="form-label">统一社会信用代码 <text class="required">*</text></view>
							<input class="form-input"
								placeholder="请输入统一社会信用代码" :value="formData.ghdwsbh" @input="(e) => handleInputChange(e, 'ghdwsbh')" />
						</view>

						<view class="form-group">
							<view class="form-label">购方地址</view>
							<input class="form-input" placeholder="请输入购方地址" :value="formData.ghdwdz"
								@input="handleInputChange" name="ghdwdz" />
						</view>

						<view class="form-group">
							<view class="form-label">购方银行</view>
							<input class="form-input" placeholder="请输入开户银行" :value="formData.ghdwyh"
								@input="handleInputChange" name="ghdwyh" />
						</view>

						<view class="form-group">
							<view class="form-label">购方账号</view>
							<input class="form-input" placeholder="请输入银行账号" :value="formData.ghdwzh"
								@input="handleInputChange" name="ghdwzh" />
						</view>
					</view>

					<!-- 销方信息 -->
					<view class="info-section">
						<view class="section-title">销方信息</view>

						<view class="form-group">
							<view class="form-label">销方名称 <text class="required">*</text></view>
							<input class="form-input readonly" value="中税师（北京）税务咨询中心" readonly />
						</view>

						<view class="form-group">
							<view class="form-label">统一社会信用代码 <text class="required">*</text></view>
							<input class="form-input readonly" value="91110108802079937H" readonly />
						</view>

						<view class="form-group">
							<view class="form-label">销方银行 <text class="required">*</text></view>
							<input class="form-input readonly" value="中国农业银行股份有限公司北京古城支行" readonly />
						</view>

						<view class="form-group">
							<view class="form-label">销方账号 <text class="required">*</text></view>
							<input class="form-input readonly" value="11031301040052826" readonly />
						</view>

						<view class="form-group">
							<view class="form-label">销方电话 <text class="required">*</text></view>
							<input class="form-input readonly" value="400-659-1213" readonly />
						</view>
					</view>
				</view>

				<!-- 发票基本信息 -->
				<view class="basic-info">
					<view class="form-row">
						<view class="form-group half">
							<view class="form-label">发票类型 <text class="required">*</text></view>
							<picker :value="formData.fplxdm" :range="invoiceTypeOptions" range-key="name"
								@change="handleInvoiceTypeChange" class="form-picker">
								<view class="picker-view">
									{{ formData.fplxdm ? getTypeName(invoiceTypeOptions, formData.fplxdm) : '请选择发票类型' }}
								</view>
							</picker>
						</view>

						<view class="form-group half">
							<view class="form-label">开票类型 <text class="required">*</text></view>
							<picker :value="formData.kplx" :range="invoiceOpenTypeOptions" range-key="name"
								@change="handleOpenTypeChange" class="form-picker">
								<view class="picker-view">
									{{ formData.kplx ? getTypeName(invoiceOpenTypeOptions, formData.kplx) : '请选择开票类型' }}
								</view>
							</picker>
						</view>

						<view class="form-group half">
							<view class="form-label">开票人 <text class="required">*</text></view>
							<input class="form-input"
								placeholder="请输入开票人姓名" :value="formData.kpr" @input="(e) => handleInputChange(e, 'kpr')" />
						</view>
					</view>
				</view>

				<!-- 发票明细 -->
				<view class="invoice-details">
					<view class="section-header">
						<view class="section-title">发票明细 <text class="required">*</text></view>
						<button class="add-row-btn" @click="addNewItem">添加行</button>
					</view>

					<view class="items-container">
						<view class="invoice-item" v-for="(item, index) in invoiceItems" :key="index">
							<view class="form-row">
								<view class="form-group third">
									<view class="form-label">序号</view>
									<input class="form-input readonly" :value="item.xh" readonly />
								</view>

								<view class="form-group third">
									<view class="form-label">含税标志</view>
									<picker :value="item.hsbz" :range="taxIncludedOptions" range-key="name"
										@change="handleTaxIncludedChange($event, index)" class="form-picker">
										<view class="picker-view">
											{{ item.hsbz === '1' ? '含税' : '不含税' }}
										</view>
									</picker>
								</view>

								<view class="form-group third">
									<view class="form-label">项目名称 <text class="required">*</text></view>
									<input class="form-input readonly" value="*非学历教育服务*培训费" readonly />
								</view>
							</view>

							<view class="form-row">
								<view class="form-group third">
									<view class="form-label">金额 <text class="required">*</text></view>
									<input class="form-input readonly" value="2298" readonly />
								</view>

								<view class="form-group third">
									<view class="form-label">税率</view>
									<picker :value="item.sl" :range="taxRateOptions" range-key="name"
										@change="handleTaxRateChange($event, index)" class="form-picker">
										<view class="picker-view">
											{{ item.sl === '0.01' ? '1%' : item.sl === '0.03' ? '3%' : '6%' }}
										</view>
									</picker>
								</view>

								<view class="form-group third">
									<view class="form-label">税额</view>
									<input class="form-input readonly" :value="item.se" readonly />
								</view>
							</view>

							<view class="delete-btn-container" v-if="invoiceItems.length > 1">
								<button class="delete-btn" @click="removeItem(index)">删除</button>
							</view>
						</view>
					</view>
				</view>

				<!-- 合计信息 -->
				<view class="summary-section">
					<view class="form-row">
						<view class="form-group third">
							<view class="form-label">合计金额</view>
							<input class="form-input readonly" :value="formData.hjje" readonly />
						</view>

						<view class="form-group third">
							<view class="form-label">合计税额</view>
							<input class="form-input readonly" :value="formData.hjse" readonly />
						</view>

						<view class="form-group third">
							<view class="form-label">价税合计</view>
							<input class="form-input readonly" :value="formData.jshj" readonly />
						</view>
					</view>

					<view class="form-group">
						<view class="form-label">价税合计（大写）</view>
						<view class="capital-summary">{{ formData.jshjdx }}</view>
					</view>
				</view>

				<!-- 备注 -->
				<view class="form-group">
					<view class="form-label">备注</view>
					<input class="form-input" placeholder="请输入备注信息" :value="formData.bz" @input="handleInputChange"
						name="bz" />
				</view>

				<!-- 提交按钮 -->
				<view class="submit-section">
					<button class="submit-btn" @click="hasDownloadableInvoice ? downloadInvoice() : submitFormData()"
						:loading="isSubmitting">
						<text v-if="hasDownloadableInvoice">
							<uni-icon type="download" size="16" class="icon-mr" />
							下载发票
						</text>
						<text v-else>{{ isSubmitting ? '提交中...' : '提交发票信息' }}</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 成功弹窗 -->
		<view class="modal-mask" v-if="isSuccessModalOpen">
			<view class="modal-container">
				<view class="modal-header">
					<view class="modal-title">发票开具成功</view>
				</view>

				<view class="modal-body">
					<view class="info-item">
						<view class="info-label">发票号码:</view>
						<view class="info-value">{{ successData.fphm }}</view>
					</view>

					<view class="info-item">
						<view class="info-label">开票日期:</view>
						<view class="info-value">{{ successData.kprq }}</view>
					</view>

					<view class="btn-group">
						<button class="modal-btn pdf-btn" @click="downloadPDF">下载PDF</button>
						<button class="modal-btn ofd-btn" @click="downloadOFD">下载OFD</button>
					</view>

					<button class="modal-btn qrcode-btn" @click="viewQrCode">查看电子票二维码</button>

					<view class="tips-container">
						<view class="tip-item red">手机端请在手机文件中查看所下载发票可传出到文件助手内使用！</view>
						<view class="tip-item blue">电脑端请在浏览器下载历史中查看所下载发票！</view>
					</view>
				</view>

				<view class="modal-footer">
					<button class="close-btn" @click="closeSuccessModal">关闭</button>
				</view>
			</view>
		</view>

		<!-- 下载弹窗 -->
		<view class="modal-mask" v-if="isDownloadModalOpen">
			<view class="modal-container">
				<view class="close-btn-modal" @click="closeDownloadModal">×</view>

				<view class="modal-body text-center">
					<view class="modal-title">{{ downloadMessage }}</view>
					<view class="modal-desc">点击下方按钮开始下载：</view>

					<button class="download-btn" @click="downloadInvoiceFile">
						点击下载发票
					</button>
				</view>

				<view class="modal-footer">
					<button class="close-btn" @click="closeDownloadModal">关闭</button>
				</view>
			</view>
		</view>

		<!-- 错误提示 -->
		<view class="error-message" v-if="submitError">
			<view class="error-icon">!</view>
			<view class="error-text">{{ submitError }}</view>
		</view>
	</view>
</template>

<script>
// 假设API配置在以下路径，如果位置不同请调整
// import { API_CONFIG } from '@/config/api.js'

export default {
	data() {
		return {
			// 表单数据
			formData: {
				ghdwdz: "",
				ghdwmc: "",
				kplx: "",
				hjse: "",
				ghdwyh: "",
				ghdwzh: "",
				xhdwdh: "400-659-1213",
				gmf_dzyx: "",
				kpr: "",
				hjje: "",
				ghdwdh: "",
				fplxdm: "",
				ghdwsbh: "",
				bz: "",
				gfxxconfirm: "",
				jshj: "",
				xhdwyh: "中国农业银行股份有限公司北京古城支行",
				zyspmc: "",
				tspz: "",
				xhdwzh: "11031301040052826",
				xh: "1",
				fphxz: "0",
				hsbz: "1", // 默认含税
				yhzcbs: "",
				jshjdx: "",
				spmc: "培训费",
				je: "2298",
				sl: "0.01",
				se: "",
				spbm: "307020102",
				dj: "",
			},

			// 发票行项目
			invoiceItems: [
				{
					xh: "1",
					hsbz: "1",
					spmc: "*非学历教育服务*培训费",
					je: "2298",
					sl: "0.01",
					se: "",
					spbm: "307020102",
					fphxz: "0",
				}
			],

			// 选项数据
			invoiceTypeOptions: [
				{ name: "数电专票", value: "81" },
				{ name: "数电普票", value: "82" }
			],

			invoiceOpenTypeOptions: [
				{ name: "正数发票开具", value: "0" },
				{ name: "负数发票开具（红冲）", value: "1" }
			],

			taxIncludedOptions: [
				{ name: "含税", value: "1" },
				{ name: "不含税", value: "0" }
			],

			taxRateOptions: [
				{ name: "1%", value: "0.01" },
				{ name: "3%", value: "0.03" },
				{ name: "6%", value: "0.06" }
			],

			// 状态管理
			

			// 下载相关状态
			isDownloadModalOpen: false,
			downloadUrl: null,
			hasDownloadableInvoice: false,
			downloadMessage: "您有已开可下载的发票",

			// 提交状态
			isSubmitting: false,
			submitError: "",

			// 成功弹窗状态
			isSuccessModalOpen: false,
			successData: null,

			// 其他状态
			userId: null,
			taxInfo: null,
			loading: true,
			error: null,
			qrCodeBase64: ""
		};
	},

	onLoad() {
		// 从本地存储获取用户信息
		const token = uni.getStorageSync('token');
		const userId = uni.getStorageSync('userId');

		if (token) {
			// 可以添加token验证逻辑
		} else {
			uni.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 2000
			});
			// 可以添加跳转登录页逻辑
		}

		if (userId) {
			this.userId = userId;
			this.fetchTaxInfo(userId);
		}
	},

	onShow() {
		// 页面显示时计算金额
		this.calculateTotals();
	},

	methods: {
		// 获取选项名称的通用方法
		getTypeName(options, value) {
			const item = options.find(item => item.value === value);
			return item ? item.name : '请选择';
		},

		// 获取税务信息
		fetchTaxInfo(userId) {
			this.loading = true;

			uni.request({
				url: `${API_CONFIG.BASE_URL}/api/tax/get`,
				method: 'POST',
				header: {
					'Content-Type': 'application/json',
					'Authorization': `Bearer ${uni.getStorageSync('token')}`
				},
				data: {
					stuId: userId,
					kplx: "0"
				},
				success: (res) => {
					if (res.statusCode === 200 && res.data) {
						this.taxInfo = res.data;

						// 检查是否有可下载的发票
						if (res.data.ewmurl) {
							this.hasDownloadableInvoice = true;
							this.downloadUrl = res.data.ewmurl;
						}

						// 更新表单数据
						if (res.data) {
							this.formData = {
								...this.formData,
								ghdwmc: res.data.ghdwmc || "",
								ghdwdh: res.data.ghdwdh || "",
								ghdwsbh: res.data.ghdwsbh || "",
							};

							// 如果有下载地址，显示下载弹窗
							if (res.data.ewmurl) {
								this.downloadUrl = res.data.ewmurl;
								this.isDownloadModalOpen = true;
							}
						}
					} else {
						this.error = '获取税务信息失败';
					}
				},
				fail: (err) => {
					console.error('获取税务信息失败:', err);
					this.error = '获取税务信息失败';
				},
				complete: () => {
					this.loading = false;
				}
			});
		},

		// 计算金额
		calculateTotals() {
			let totalAmount = 0;
			let totalTax = 0;

			this.invoiceItems.forEach(item => {
				const amount = parseFloat(item.je) || 0;
				const taxRate = parseFloat(item.sl) || 0;

				if (item.hsbz === "1") { // 含税
					const tax = amount * taxRate / (1 + taxRate);
					totalAmount += amount - tax;
					totalTax += tax;
				} else { // 不含税
					const tax = amount * taxRate;
					totalAmount += amount;
					totalTax += tax;
				}
			});

			// 更新表单数据
			this.formData.hjje = totalAmount.toFixed(2);
			this.formData.hjse = totalTax.toFixed(2);
			this.formData.se = totalTax.toFixed(2);
			this.formData.jshj = (totalAmount + totalTax).toFixed(2);
			this.formData.jshjdx = this.toChineseNumber(totalAmount + totalTax);

			// 更新每个项目的税额
			this.invoiceItems = this.invoiceItems.map(item => {
				const amount = parseFloat(item.je) || 0;
				const taxRate = parseFloat(item.sl) || 0;
				let se = 0;

				if (item.hsbz === "1") { // 含税
					se = amount * taxRate / (1 + taxRate);
				} else { // 不含税
					se = amount * taxRate;
				}

				return { ...item, se: se.toFixed(2) };
			});
		},

		// 转换数字为中文大写
		toChineseNumber(n) {
			const fraction = ['角', '分'];
			const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
			const unit = ['元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];

			let num = Math.abs(n);
			let s = '';

			for (let i = 0; i < fraction.length; i++) {
				const digitValue = Math.floor(num * 10 * Math.pow(10, i)) % 10;
				s += (digit[digitValue] + fraction[i]).replace(/零./, '');
			}

			s = s || '整';
			num = Math.floor(num);

			for (let i = 0; i < unit.length && num > 0; i++) {
				s = digit[num % 10] + unit[i] + s;
				num = Math.floor(num / 10);
			}

			return s.replace(/(零.)*零元/, '元')
				.replace(/(零.)+/g, '零')
				.replace(/^整$/, '零元整');
		},

		// 处理输入变化
		handleInputChange(e, name) {
			const value = e.detail ? e.detail.value : e.target.value;
			console.log('输入事件对象:', e); // 调试日志
			console.log('输入变化:', name, '=', value); // 调试日志
			if (name && this.formData) {
				this.$set(this.formData, name, value); // 确保响应式更新
				if (this.validationErrors) this.validationErrors[name] = false;
			}
			console.log('当前表单数据:', JSON.stringify(this.formData, null, 2)); // 调试日志
		},

		// 处理发票类型变化
		handleInvoiceTypeChange(e) {
			if (!this.formData) this.formData = {};
			const value = this.invoiceTypeOptions[e.detail.value].value;
			this.formData.fplxdm = value;
			if (this.validationErrors) this.validationErrors.fplxdm = false;
		},

		// 处理开票类型变化
		handleOpenTypeChange(e) {
			if (!this.formData) this.formData = {};
			const value = this.invoiceOpenTypeOptions[e.detail.value].value;
			this.formData.kplx = value;
			if (this.validationErrors) this.validationErrors.kplx = false;
		},

		// 处理含税标志变化
		handleTaxIncludedChange(e, index) {
			const value = this.taxIncludedOptions[e.detail.value].value;

			const newItems = [...this.invoiceItems];
			newItems[index].hsbz = value;

			this.invoiceItems = newItems;
			this.calculateTotals();
		},

		// 处理税率变化
		handleTaxRateChange(e, index) {
			const value = this.taxRateOptions[e.detail.value].value;

			const newItems = [...this.invoiceItems];
			newItems[index].sl = value;

			this.invoiceItems = newItems;
			this.calculateTotals();
		},

		// 添加新行
		addNewItem() {
			const newItems = [...this.invoiceItems];
			newItems.push({
				xh: `${newItems.length + 1}`,
				hsbz: newItems[0].hsbz,
				spmc: "*非学历教育服务*培训费",
				je: "2298",
				sl: newItems[0].sl,
				se: "",
				spbm: "307020102",
				fphxz: "0",
			});

			this.invoiceItems = newItems;
			this.calculateTotals();
		},

		// 删除行
		removeItem(index) {
			if (this.invoiceItems.length <= 1) {
				uni.showToast({
					title: '至少保留一行',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			let newItems = [...this.invoiceItems];
			newItems.splice(index, 1);

			// 重新排序序号
			newItems = newItems.map((item, i) => ({ ...item, xh: `${i + 1}` }));

			this.invoiceItems = newItems;
			this.calculateTotals();
		},

		// 表单验证
		validateForm() {
			const errors = {
				ghdwmc: !this.formData.ghdwmc.trim(),
				ghdwdh: !this.formData.ghdwdh.trim(),
				ghdwsbh: !this.formData.ghdwsbh.trim(),
				fplxdm: !this.formData.fplxdm,
				kplx: !this.formData.kplx,
				kpr: !this.formData.kpr.trim()
			};

			this.validationErrors = errors;
			return !Object.values(errors).some(error => error);
		},

		// 提交表单
		submitFormData() {
			this.isSubmitting = true;
			this.submitError = "";

			// 调试输出表单数据
			console.log('表单提交数据:', JSON.stringify({
				ghdwmc: this.formData.ghdwmc,
				ghdwdh: this.formData.ghdwdh,
				ghdwsbh: this.formData.ghdwsbh,
				kpr: this.formData.kpr,
				fplxdm: this.formData.fplxdm,
				kplx: this.formData.kplx
			}, null, 2));

			// 验证必填字段
			const requiredFields = {
				ghdwmc: "购方名称",
				ghdwdh: "购方电话",
				ghdwsbh: "统一社会信用代码",
				fplxdm: "发票类型",
				kplx: "开票类型",
				kpr: "开票人"
			};

			const missingFields = Object.entries(requiredFields)
				.filter(([field]) => {
					const value = this.formData[field];
					const isEmpty = value === undefined || value === null || String(value).trim() === "";
					console.log(`字段 ${field} 检查结果:`, isEmpty ? '空' : '已填', '值:', value);
					return isEmpty;
				})
				.map(([_, name]) => name);

			if (missingFields.length > 0) {
				this.submitError = `请填写以下必填字段：${missingFields.join(", ")}`;
				this.isSubmitting = false;
				return;
			}

			// 准备请求数据
			const requestData = {
				...this.formData,
				gmfmc: this.formData.ghdwmc || "",
				ghdwmc: this.formData.ghdwmc || "",
				ghdwdh: this.formData.ghdwdh || "",
				ghdwsbh: this.formData.ghdwsbh || "",
				fplxdm: this.formData.fplxdm || "",
				kplx: this.formData.kplx || "",
				kpr: this.formData.kpr || "",
				invoiceItems: this.invoiceItems.map(item => ({
					...item,
					je: parseFloat(item.je).toFixed(2),
					sl: parseFloat(item.sl).toFixed(4),
					se: parseFloat(item.se).toFixed(2)
				}))
			};

			uni.request({
				url: `https://www.xn--fiq799a58u.xn--fiqs8s/api/invoice?stuId=${this.userId}`,
				method: 'POST',
				header: {
					'Content-Type': 'application/json',
					'Authorization': `Bearer ${uni.getStorageSync('token')}`
				},
				data: requestData,
				success: (res) => {
					if (res.statusCode === 200 && res.data && res.data.code === "00000") {
						this.isSuccessModalOpen = true;
						this.successData = {
							fphm: res.data.data.fphm,
							kprq: res.data.data.kprq,
							pdfUrl: res.data.data.pdf_url,
							ofdUrl: res.data.data.ofd_url,
							ewmUrl: res.data.data.ewm_url
						};
						this.hasDownloadableInvoice = true;
						this.downloadUrl = res.data.data.ewm_url;
					} else {
						this.submitError = res.data?.msg || '发票开具失败';
					}
				},
				fail: (err) => {
					console.error('开票失败:', err);
					this.submitError = '发票开具失败，请检查数据后重试';
				},
				complete: () => {
					this.isSubmitting = false;
				}
			});
		},

		// 下载发票
		downloadInvoice() {
			if (this.downloadUrl) {
				uni.downloadFile({
					url: this.downloadUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								success: (res) => {
									console.log('打开文档成功');
								}
							});
						}
					},
					fail: (err) => {
						console.error('下载失败:', err);
						uni.showToast({
							title: '下载失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			}
		},

		// 下载PDF
		downloadPDF() {
			if (this.successData?.pdfUrl) {
				uni.showLoading({ title: '下载PDF中...' });
				uni.downloadFile({
					url: this.successData.pdfUrl,
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								fileType: 'pdf',
								success: () => {
									console.log('PDF打开成功');
								},
								fail: (err) => {
									console.error('PDF打开失败:', err);
									uni.showToast({
										title: 'PDF打开失败',
										icon: 'none',
										duration: 2000
									});
								}
							});
						} else {
							uni.showToast({
								title: 'PDF下载失败',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('PDF下载失败:', err);
						uni.showToast({
							title: 'PDF下载失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			}
		},

		// 下载OFD
		downloadOFD() {
			if (this.successData?.ofdUrl) {
				this.downloadFile(this.successData.ofdUrl, 'OFD');
			}
		},

		// 通用下载方法
		downloadFile(url, type) {
			uni.showLoading({ title: `下载${type}中...` });

			uni.downloadFile({
				url: url,
				success: (res) => {
					uni.hideLoading();

					if (res.statusCode === 200) {
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true,
							fileType: type.toLowerCase(),
							success: () => {
								console.log(`${type}打开成功`);
							},
							fail: (err) => {
								console.error(`${type}打开失败:`, err);
								uni.showToast({
									title: `${type}打开打开失败`,
									icon: 'none',
									duration: 2000
								});
							}
						});
					} else {
						uni.showToast({
							title: `${type}下载失败`,
							icon: 'none',
							duration: 2000
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error(`${type}下载失败:`, err);
					uni.showToast({
						title: `${type}下载失败`,
						icon: 'none',
						duration: 2000
					});
				}
			});
		},

		// 查看二维码
		viewQrCode() {
			if (this.successData?.ewmUrl) {
				uni.navigateTo({
					url: `/pages/qrcode/index?url=${encodeURIComponent(this.successData.ewmUrl)}`
				});
			}
		},

		// 关闭成功弹窗
		closeSuccessModal() {
			this.isSuccessModalOpen = false;
		},

		// 关闭下载弹窗
		closeDownloadModal() {
			this.isDownloadModalOpen = false;
		},

		// 下载发票文件
		downloadInvoiceFile() {
			if (this.downloadUrl) {
				uni.downloadFile({
					url: this.downloadUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								success: () => {
									this.closeDownloadModal();
								}
							});
						}
					},
					fail: (err) => {
						console.error('下载失败:', err);
						uni.showToast({
							title: '下载失败',
							icon: 'none',
							duration: 2000
						});
					} 	
				});
			}
		}
	}
};
</script>

<style>
page {
	background-color: #f5f5f5;
	min-height: 100%;
	padding-bottom: 30rpx;
}

.container {
	padding: 20rpx;
}

.form-card {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	text-align: center;
	margin-bottom: 40rpx;
}

.info-container {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
	margin-bottom: 30rpx;
}

@media (min-width: 768px) {
	.info-container {
		flex-direction: row;
		gap: 40rpx;
	}

	.info-section {
		flex: 1;
	}
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	padding-bottom: 15rpx;
	border-bottom: 1px solid #eee;
	margin-bottom: 20rpx;
}

.form-group {
	margin-bottom: 25rpx;
}

/* 调整标签与输入框的间距，保持整体协调 */
.form-label {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 12rpx; /* 适当增加标签与输入框的距离 */
}

.required {
	color: #ff4d4f;
}

.form-input {
  width: 100%;
  /* 增加上下内边距，提高输入框高度 */
  padding: 20rpx 16rpx; 
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx; /* 适当增大字体，避免文字显得拥挤 */
  box-sizing: border-box;
  /* 确保输入框有足够高度容纳文字，避免压缩 */
  min-height: 80rpx; 
  line-height: 40rpx; /* 与字体大小匹配，保证文字垂直居中 */
}

.form-input.readonly {
	background-color: #f5f5f5;
	color: #666;
}

.error-input {
	border-color: #ff4d4f !important;
	background-color: #fff2f0 !important;
}

.error-text {
	color: #ff4d4f;
	font-size: 22rpx;
	margin-top: 5rpx;
	min-height: 24rpx;
}

.form-row {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	margin-bottom: 25rpx;
}

.half {
	flex: 1;
	min-width: calc(50% - 10rpx);
}

.third {
	flex: 1;
	min-width: calc(33.333% - 14rpx);
}

@media (max-width: 767px) {

	.half,
	.third {
		min-width: 100%;
	}
}

/* 同步调整选择器（picker）的样式，保持一致性 */
.form-picker {
  position: relative;
  width: 100%;
  padding: 20rpx 16rpx; /* 与输入框保持相同内边距 */
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx; /* 与输入框字体大小一致 */
  box-sizing: border-box;
  min-height: 80rpx; /* 与输入框高度一致 */
  line-height: 40rpx;
}


/* 调整选择器内部文字容器的样式 */
.picker-view {
  display: flex;
  align-items: center;
  min-height: 40rpx; /* 确保文字有足够空间 */
}


.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.add-row-btn {
	background-color: #52c41a;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	height: auto;
	line-height: normal;
}

.items-container {
	margin-bottom: 30rpx;
}

.invoice-item {
	border: 1px solid #eee;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	position: relative;
}

.delete-btn-container {
	display: flex;
	justify-content: flex-end;
	margin-top: 10rpx;
}

.delete-btn {
	color: #ff4d4f;
	border: 1px solid #ff4d4f;
	background-color: transparent;
	border-radius: 8rpx;
	padding: 5rpx 15rpx;
	font-size: 24rpx;
	height: auto;
	line-height: normal;
}

.summary-section {
	background-color: #f9f9f9;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 30rpx;
}

.capital-summary {
	width: 100%;
	padding: 14rpx 16rpx;
	border: 1px solid #ddd;
	border-radius: 8rpx;
	font-size: 26rpx;
	background-color: #fff;
	min-height: 54rpx;
	box-sizing: border-box;
}

.submit-section {
	margin-top: 40rpx;
}

.submit-btn {
	width: 100%;
	background-color: #1890ff;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 16rpx 0;
	font-size: 28rpx;
	font-weight: 500;
}

.icon-mr {
	margin-right: 10rpx;
}

/* 弹窗样式 */
.modal-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.7);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 999;
}

.modal-container {
	width: 90%;
	max-width: 600rpx;
	background-color: #fff;
	border-radius: 16rpx;
	overflow: hidden;
	position: relative;
}

.modal-header {
	padding: 25rpx 30rpx;
	border-bottom: 1px solid #eee;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	text-align: center;
}

.modal-body {
	padding: 30rpx;
}

.modal-footer {
	padding: 20rpx 30rpx;
	border-top: 1px solid #eee;
	display: flex;
	justify-content: center;
}

.close-btn {
	padding: 10rpx 40rpx;
	background-color: #f5f5f5;
	color: #333;
	border: none;
	border-radius: 8rpx;
	font-size: 26rpx;
	height: auto;
	line-height: normal;
}

.info-item {
	display: flex;
	margin-bottom: 20rpx;
}

.info-label {
	flex: 0 0 160rpx;
	font-weight: 500;
	font-size: 26rpx;
}

.info-value {
	flex: 1;
	font-size: 26rpx;
}

.btn-group {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.modal-btn {
	flex: 1;
	padding: 15rpx 0;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	font-size: 26rpx;
	height: auto;
	line-height: normal;
}

.pdf-btn {
	background-color: #f5222d;
}

.ofd-btn {
	background-color: #1890ff;
}

.qrcode-btn {
	background-color: #52c41a;
	width: 100%;
	margin-bottom: 20rpx;
}

.tips-container {
	margin-top: 20rpx;
}

.tip-item {
	padding: 15rpx;
	border-radius: 8rpx;
	color: #fff;
	font-size: 24rpx;
	margin-bottom: 15rpx;
}

.tip-item.red {
	background-color: #f5222d;
}

.tip-item.blue {
	background-color: #1890ff;
}

.close-btn-modal {
	position: absolute;
	top: 15rpx;
	right: 15rpx;
	font-size: 40rpx;
	color: #999;
}

.text-center {
	text-align: center;
}

.modal-desc {
	font-size: 26rpx;
	color: #666;
	margin: 20rpx 0 30rpx;
}

.download-btn {
	background-color: #1890ff;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 15rpx 0;
	font-size: 28rpx;
	width: 100%;
	margin-bottom: 20rpx;
	height: auto;
	line-height: normal;
}

.error-message {
	background-color: #fff2f0;
	border: 1px solid #ffccc7;
	color: #ff4d4f;
	padding: 15rpx 20rpx;
	border-radius: 8rpx;
	margin: 20rpx 0;
	display: flex;
	align-items: center;
}

.error-icon {
	background-color: #ff4d4f;
	color: #fff;
	border-radius: 50%;
	width: 30rpx;
	height: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-right: 10rpx;
	font-size: 20rpx;
	font-weight: bold;
}

.error-text {
	flex: 1;
	font-size: 26rpx;
}
</style>